package com.linkdood.app.utils;

import com.linkdood.app.service.ddio.TemplateMessage;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.List;

/**
 * 文件 工具类
 * @author gaoliusheng
 */
public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    private static final String HTTPS_PREFIX = "https";

    public static void compressFiles2ZipSync(List<File> localFiles, File zipFile, List<String> realFilenames) {
        Boolean verification = compressedFileVerification(localFiles, zipFile, realFilenames);
        if(verification){
            compressFiles2ZipProcess(localFiles, zipFile, realFilenames);
        }
    }

    /**
     * 对压缩文件进行初步校验
     * @return 校验成功返回true, 否则返回false
     */
    public static Boolean compressedFileVerification(List<File> localFiles, File zipFile, List<String> realFilenames){
        if (CollectionUtils.isEmpty(localFiles) || Collections.isEmpty(realFilenames)) {
            logger.error("LocalFiles or realFilename is empty");
            return false;
        }
        if (realFilenames.size() != localFiles.size()) {
            logger.error("Inconsistent number of files");
            return false;
        }
        if (!isEndWithZip(zipFile.getName())) {
            logger.error("ZipFile is not end with zip");
            return false;
        }
        return true;
    }

    /**
     * 对文件进行压缩
     */
    public static void compressFiles2ZipProcess(List<File> localFiles, File zipFile, List<String> realFilenames) {
        try (ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(zipFile)) {
            zaos.setUseZip64(Zip64Mode.AsNeeded);
            for (int i = 0; i < localFiles.size(); i++) {
                File file = localFiles.get(i);
                if (file == null) {
                    continue;
                }
                zaos.putArchiveEntry(new ZipArchiveEntry(file, realFilenames.get(i)));
                try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
                    byte[] buffer = new byte[1024 * 5];
                    int len = -1;
                    while ((len = is.read(buffer)) != -1) {
                        zaos.write(buffer, 0, len);
                    }
                    zaos.closeArchiveEntry();
                } catch (Exception e) {
                    logger.error("ZipArchiveOutputStream write error:{}", e.getMessage());
                }
            }
            zaos.finish();
        } catch (Exception e) {
            logger.error("Compress {} error: {}", zipFile.getName(), e.getMessage());
        }
    }

    /**
     * 判断文件名是否以.zip为后缀
     *
     * @return 是zip文件返回true, 否则返回false
     */
    public static boolean isEndWithZip(String filename) {
        if (StringUtils.isEmpty(filename)) {
            return false;
        }
        return filename.trim().toLowerCase().endsWith(".zip");
    }
}
